package cn.zn.dept.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.dept.entity.SysCorp;
import cn.zn.dept.mapper.SysCorpMapper;
import cn.zn.dept.service.SysCorpService;
import cn.zn.menu.dto.TreeSelectDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn-admin
 * @since 2021-03-04
 */
@Service
public class SysCorpServiceImpl extends ServiceImpl<SysCorpMapper, SysCorp> implements SysCorpService {

    @Override
    public List<TreeSelectDto> selectCorpTree() {
        List<TreeSelectDto> treeList = new ArrayList<>();

        List<SysCorp> corps = selectCorpList();
        if (CollUtil.isNotEmpty(corps)) {
            findTreeList(treeList, corps);
        }
        return treeList;
    }

    private void findTreeList(List<TreeSelectDto> treeList, List<SysCorp> corps) {
        for (SysCorp corp : corps) {
            boolean has = false;
            for (TreeSelectDto tree : treeList) {
                if (StrUtil.equals(corp.getIndustryId(), tree.getId())) {
                    TreeSelectDto treeSelectDto = new TreeSelectDto();
                    treeSelectDto.setId(corp.getId());
                    treeSelectDto.setLabel(corp.getCorpName());
                    tree.getChildren().add(treeSelectDto);

                    has = true;
                    break;
                }
            }
            if (!has) {
                TreeSelectDto child = new TreeSelectDto();
                child.setId(corp.getId());
                child.setLabel(corp.getCorpName());
                List<TreeSelectDto> children = new ArrayList<>();
                children.add(child);

                TreeSelectDto treeSelectDto = new TreeSelectDto();
                treeSelectDto.setId(corp.getIndustryId());
                treeSelectDto.setLabel(corp.getIndustryName());
                treeSelectDto.setChildren(children);
                treeList.add(treeSelectDto);
            }
        }
    }

    @Override
    public List<SysCorp> selectCorpList() {
        QueryWrapper<SysCorp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STATUS", "0");
        queryWrapper.orderByAsc("CORP_CODE");
        return baseMapper.selectList(queryWrapper);
    }

}
